#pragma once

#include <sys/epoll.h>
#include "Log.hpp"
#include <cerrno>
#include <cstring>
#include "nocopy.hpp"

const int num = 128; // default rb_nood

Log lg;

class Epoll : public nocopy
{
public:
    Epoll()
    {
        _epfd = epoll_create(num);
        if (_epfd == -1)
        {
            lg(Warning, "epoll create error, error:%d, error thing:%s", errno, strerror(errno));
        }
        else
        {
            lg(Info, "epoll create success, epfd:%d", _epfd);
        }
    }

    int EpollWait(struct epoll_event revs[], int num, int timeout)
    {
        int n = epoll_wait(_epfd, revs, num, timeout);
        return n;
    }

    int EpollUpdate(int op, int sock, uint32_t even)
    {
        int n = 0;
        if (op == EPOLL_CTL_DEL)
        {
            n = epoll_ctl(_epfd, op, sock, nullptr);
            if (n != 0)
            {
                lg(Warning, "epoll ctl del error, errno:%d, error thing: %s", errno, strerror(errno));
            }
        }
        else if (op == EPOLL_CTL_ADD || op == EPOLL_CTL_MOD)
        {
            struct epoll_event ev;
            ev.data.fd = sock;
            ev.events = even;

            n = epoll_ctl(_epfd, op, sock, &ev);
            if (n != 0)
            {
                lg(Warning, "epoll ctl error");
            }
        }

        return n;
    }

    ~Epoll()
    {
        if (_epfd > 0)
            close(_epfd);
    }

private:
    int _epfd;
};
